//
//  LWLogInVc.m
//  LWShopItem
//
//  Created by mac on 17/4/25.
//  Copyright © 2017年 LWShop.com. All rights reserved.
//

#import "LWLogInVc.h"
#import <CommonCrypto/CommonCrypto.h>
#import <AFNetworking.h>
#import "SVProgressHUD.h"
#import "LWHomeViewController.h"
#import "SVProgressHUD.h"
#import "LWHeaderView.h"

#import "DWWXSDK.h"



@interface LWLogInVc ()<UITextFieldDelegate>

/**
 登陆用手机号
 */
@property (weak, nonatomic) IBOutlet UITextField *phoneNumberTField;

/**
 获取验证码按钮
 */
@property (weak, nonatomic) IBOutlet UIButton *getSecurityCodeBtn;

/**
 验证码输入框
 */
@property (weak, nonatomic) IBOutlet UITextField *securityCodeInputTField;

/**
 登陆按钮
 */
@property (weak, nonatomic) IBOutlet UIButton *logInBtn;

//倒计时
@property(assign, nonatomic) NSInteger timeCount;

//验证时间
@property(strong, nonatomic) NSTimer *timer;



@end

@implementation LWLogInVc

{
    UITextField *_account;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupUI];
    
}
#pragma MARK -UI
- (void)setupUI
{
    
    self.phoneNumberTField.delegate = self;
    
    UIButton *disBtn = [UIButton new];
    [disBtn setImage:[UIImage imageNamed:@"close"] forState:UIControlStateNormal];
    
    [disBtn addTarget:self action:@selector(disBtnClick) forControlEvents:UIControlEventTouchUpInside];
    
    disBtn.frame = CGRectMake(10, 10, 40, 40);
    
    [self.view addSubview:disBtn];
    
    
    
}

- (void)disBtnClick
{
    [self dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark - UITextFieldDelegate

//只允许输入数字，且只有11位数
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    //    NSLog(@"%@", NSStringFromRange(range));
    
    if (self.phoneNumberTField.text.length == 11) {
        if ([string isEqualToString:@""]) {
            return YES;
        }
        else {
            return NO;
        }
    }
    
    if (self.phoneNumberTField.text.length == 10 && [self validateNumber:string]) {
        [self.getSecurityCodeBtn setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
        
        
    }
    return [self validateNumber:string];
}
//只允许输入数字
- (BOOL)validateNumber:(NSString*)number{
    BOOL res = YES;
    NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
    int i = 0;
    while (i < number.length) {
        NSString * string = [number substringWithRange:NSMakeRange(i, 1)];
        NSRange range = [string rangeOfCharacterFromSet:tmpSet];
        if (range.length == 0) {
            res = NO;
            break;
        }
        i++;
    }
    return res;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [_phoneNumberTField resignFirstResponder];
    [_securityCodeInputTField resignFirstResponder];
}


#pragma mark - Btn click action
- (IBAction)getSecurityCodeBtnClick:(id)sender
{
    
    if (_phoneNumberTField.hasText && _phoneNumberTField.text.length == 11) {
        
        
        [self.getSecurityCodeBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
        
        
        //倒计时
        self.timeCount = 60;
        self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(reduceTime:) userInfo:sender repeats:YES];
        
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        dic[@"mobile"] = self.phoneNumberTField.text;
        [HYBNetworking postWithUrl:@"index.php?m=Api&c=User&a=send_sms_reg_code" refreshCache:YES params:[LWUtilityClass isDict:dic] success:^(id response) {
            if ([response[@"status"] isEqual:@1]) {
                [self timer];
            }else{
                
                [SVProgressHUD showWithStatus:@"请输入正确的手机号码"];
                
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    
                    [SVProgressHUD setAnimationDelay:1.5];
                    
                    [SVProgressHUD dismissWithDelay:1.5];
                    
                });
                
                
            }
        } fail:^(NSError *error) {
            
            
            [SVProgressHUD showWithStatus:@"网络异常,请稍后在试"];
            
        }];

        
        
    }else
    {
        _getSecurityCodeBtn.enabled = YES;
    }
    

}

#pragma mark - 短信验证倒计时
- (void)reduceTime:(NSTimer *)codeTimer {
    
    self.timeCount--;
    if (self.timeCount == 0) {
        [_getSecurityCodeBtn setTitle:@"重新获取验证码" forState:UIControlStateNormal];
        [_getSecurityCodeBtn setTitleColor:[UIColor colorWithRed:248/255.0f green:144/255.0f blue:34/255.0f alpha:1] forState:UIControlStateNormal];
        UIButton *info = codeTimer.userInfo;
        info.enabled = YES;
        _getSecurityCodeBtn.userInteractionEnabled = YES;
        [self.timer invalidate];
    } else {
        NSString *str = [NSString stringWithFormat:@"%lu秒后重新获取", self.timeCount];
        [_getSecurityCodeBtn setTitle:str forState:UIControlStateNormal];
        _getSecurityCodeBtn.userInteractionEnabled = NO;
    }
}
#pragma mark - sigInBtn
- (IBAction)sigInBtn
{
    
    if (!(_securityCodeInputTField.text.length && _phoneNumberTField.text.length)){return ;}
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    dic[@"code"] = self.securityCodeInputTField.text;
    dic[@"mobile"] = self.phoneNumberTField.text;
    [HYBNetworking postWithUrl:@"index.php?m=Api&c=User&a=newreg" refreshCache:YES params:[LWUtilityClass isDict:dic] success:^(id response) {
        if ([response[@"status"] isEqual:@1]) {
            [SVProgressHUD showSuccessWithStatus:@"登陆成功"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [SVProgressHUD dismiss];
                // 保存手机号和密码值
                [[NSUserDefaults standardUserDefaults] setValue:response[@"result"][@"nickname"] forKey:@"nickName"];
                
                NSLog(@"%@",response[@"result"][@"nickname"]);
                
                [[NSUserDefaults standardUserDefaults] setValue:response[@"result"][@"token"] forKey:@"token"];
                
                NSLog(@"%@",response[@"result"][@"token"]);
                
                [[NSUserDefaults standardUserDefaults] setValue:response[@"result"][@"user_id"] forKey:@"user_id"];
                
                NSLog(@"%@",response[@"result"][@"user_id"]);
                
                [self dismissViewControllerAnimated:YES completion:nil];
            });
        }else{
            [self showAlert:@"您输入的验证码不正确，请从新输入"];
        }
    } fail:^(NSError *error) {
        [SVProgressHUD showWithStatus:@"网络异常,请稍后在试"];
    }];

}

#pragma MARK - 微信登录
- (IBAction)weChatLogInBtn
{
    NSLog(@"点击了微信登录");
    
    DWWXSDK *wxsdk = [DWWXSDK wxSDK];
    [wxsdk dw_wxLoginOAuthWXAppid:@"wxd21cf7d764a8a393" wxSecret:@"88704af549141ff62c5b1413f1697981" wxState:@"123" successBlock:^(DWWeChatProfileModel *profileModel) {
        
        NSLog(@"%@\n%@\n%@", profileModel.nickname, profileModel.headimgurl, profileModel.unionid);
      
        NSLog(@"%@", [NSThread currentThread]);
        
    } errorBlock:^(NSError *error, NSInteger errcode, NSString *errmsg) {
        
        NSLog(@"%@\n%ld\n%@", error, errcode, errmsg);
        
    }];
    
    //发送通知
    [[NSNotificationCenter defaultCenter]postNotificationName:@"nameNote" object:nil userInfo:nil];
    
   [self dismissViewControllerAnimated:YES completion:nil];

}

#pragma mark - HUDMETHOD
-(void)dismissMy{
    
    [SVProgressHUD dismiss];
    [self dismissViewControllerAnimated:YES completion:nil];
    
}
#pragma mark - alertView
- (void)timerFireMethod:(NSTimer*)theTimer//弹出框
{
    UIAlertView *promptAlert = (UIAlertView*)[theTimer userInfo];
    [promptAlert dismissWithClickedButtonIndex:0 animated:NO];
    promptAlert =NULL;
}
- (void)showAlert:(NSString *) _message{
    //时间
    UIAlertView *promptAlert = [[UIAlertView alloc] initWithTitle:@"提示:" message:_message delegate:nil cancelButtonTitle:nil otherButtonTitles:nil];
    
    [NSTimer scheduledTimerWithTimeInterval:1.5f
                                     target:self
                                   selector:@selector(timerFireMethod:)
                                   userInfo:promptAlert
                                    repeats:YES];
    [promptAlert show];
}

#pragma mark - HUD
-(void)SVPMethodWith:(NSString *) Message{
    
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
    [SVProgressHUD setMinimumDismissTimeInterval:0.5];
    [SVProgressHUD setDefaultAnimationType:SVProgressHUDAnimationTypeNative];
    [SVProgressHUD showInfoWithStatus:Message];
    
    
}




@end
